#include "homewindow.h"
#include "config/config.h"
#include "config/constant.h"
#include "ui_homewindow.h"
#include <BinaryFileUtil.h>
#include <PathUtils.h>
#include <QMessageBox>
#include <QPushButton>
#include <QStackedLayout>
#include <messageboxutils.h>
#include <qlabel.h>
#include <setting_service_dao.h>
#include "db/dbservice.cpp"
#include "widget/qpushbuttonwidget.h"
#include <dialog/baudrate_dialog.h>
#include    <QMessageBox>
#include    <QCloseEvent>
#include    <QTimer>
#include <service/serialportservice.h>
#include <widget/ecggridwidget.h>
#include <widget/ecgwavewidget.h>
HomeWindow::HomeWindow(QWidget *parent)
    : BaseWindow(parent), ui(new Ui::HomeWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("单导心电设备监测软件");
    //初始化路径
    Config::initAppPaths();
    Config::writeLog("应用程序启动");
    qDebug() << "当前版本:" << Config::VERSION;
    //初始化数据库
    DbService::initDatabase();
    Setting *setting = SettingServiceDao::instance().getSetting(Constant::BAUDRATE);
    if (setting) {
        qDebug() << "波特率设置:" << setting->property("value").toInt();
        baudRate = setting->property("value").toInt();
    } else {
        qDebug() << "未找到波特率设置，使用默认值:" << baudRate;
    }
    //初始化串口服务
    initSerialPortService();
    //初始化心电图组件
    initECGWidget();
    //初始化增益
    initGainAndSpeed();
    //初始化模拟数据
    initSimulateData();
    //初始化耗时数据处理
    setupWorker();
}
void HomeWindow::showEvent(QShowEvent *event)
{
    BaseWindow::showEvent(event);
    qDebug("HomeWindow showEvent....");
}
HomeWindow::~HomeWindow()
{
    delete ui;
    if( serialPortService){
        serialPortService->disconnectPort();
    }
    delete serialPortService;
    delete wave;
    if(m_worker){
         m_worker->stop();
        delete m_worker;
        m_worker = nullptr;
    }
}
void HomeWindow::initStyle()
{
    BaseWindow::initStyle();
    qDebug("HomeWindow initstyle....");
}
void HomeWindow::initUI()
{
    BaseWindow::initUI();
    qDebug("HomeWindow initUI....");
    if( !is_initUi ){
        initStatusBar();
        initMenuBar();
        is_initUi = !is_initUi;
    }
}
///底部状态的标签
void HomeWindow::initStatusBar(){
    labViewCord=new QLabel("心电设备未连接"); //创建状态栏上的标签
    labViewCord->setMinimumWidth(150);
    labViewCord->setStyleSheet(
        "color: #ffffff;"
        // "background-color: #aee;"
        // "border: 1px solid #666;"
        // "border-radius: 5px;"
        "padding: 3px 8px;"
        "font-size:14px;"
        );
    ui->statusbar->addWidget(labViewCord);
    //添加一个状态按钮
    btnLinkDevice = new QPushButton("断开设备");
    btnLinkDevice->setStyleSheet(
        "QPushButton {"
        "   color: #ffffff;"
        "   background-color: #f92f51;"
        "   border: none;"
        "   border-radius: 5px;"
        "   padding: 5px 10px;"
        "   font-size: 14px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #f92fff;"
        "}"
        );
    btnLinkDevice->setVisible( isConnect );
    connect(btnLinkDevice, &QPushButton::clicked, this, &HomeWindow::onConnectButtonClicked);
    ui->statusbar->addWidget(btnLinkDevice);
    //在末尾加一个布局
    labViewMessage=new QLabel("测量信息：--"); //创建状态栏上的标签
    labViewMessage->setMinimumWidth(150);
    labViewMessage->setStyleSheet(
        "color: #ffffff;"
        // "background-color: #aee;"
        // "border: 1px solid #666;"
        // "border-radius: 5px;"
        "padding: 3px 8px;"
        "font-size:14px;"
        );
    ui->statusbar->addPermanentWidget(labViewMessage);
    //取消状态栏item分割线
    ui->statusbar->setStyleSheet("QStatusBar::item { border: none; }");
}
//连接设备按钮点击事件
void HomeWindow::onConnectButtonClicked()
{
    qDebug("断开设备");
    if( serialPortService->isConnected() ){
        serialPortService->disconnectPort();
        isConnect = false;
        btnLinkDevice->setVisible( isConnect );
        MessageBoxUtils::showAutoCloseMessageBox(this, "提示", "已经断开连接",500);
        return;
    }
}
//初始化菜单栏
void HomeWindow::initMenuBar(){
    qDebug("HomeWindow::initMenuBar");
    QMenuBar *menuBar = ui->menubar;
    QMenu *sMenu = menuBar->addMenu("设置");
    QAction *newAct = new QAction("设置波特率", this);
    QAction *openAct = new QAction("连接设备", this);
    //QAction *openLocalDataAct = new QAction("使用本地数据", this);
    QAction *exitAct = new QAction("退出(&X)", this);
    sMenu->addAction(newAct);
    sMenu->addAction(openAct);
    //sMenu->addAction(openLocalDataAct);
    sMenu->addSeparator();  // 添加分隔线
    sMenu->addAction(exitAct);
    connect(exitAct, &QAction::triggered, this, &QWidget::close);
    //设置波特率
    connect(newAct, &QAction::triggered, this,&HomeWindow::on_action_triggered);
    //连接设备
    connect(openAct, &QAction::triggered, this,[this](){
        qDebug() << "连接设备" << serialPortService;
        if( serialPortService->isConnected() ){
            MessageBoxUtils::showAutoCloseMessageBox(this, "提示", "设备已连接，无需重复连接！");
            return;
        }
        qDebug() << "连接设备2" << serialPortService;
        serialPortService->connectToPort("", baudRate, true);
    });
    //使用本地数据
    // connect(openLocalDataAct, &QAction::triggered, this,[this](){
    //     qDebug("使用本地数据");
    // });

    QMenu *hMenu = menuBar->addMenu("帮助");
    QAction *aboutAct = new QAction("关于", this);
    hMenu->addAction(aboutAct);
    connect(aboutAct, &QAction::triggered, this,[](){
        QMessageBox::about(nullptr, "关于软件", "一个串口心电设备监测软件\n作者: @lion.bai\n版本: 1.0");
    });
}
//设置波特率
void HomeWindow::on_action_triggered()
{
    qDebug("设置波特率");
    if( dlgBaudRate == nullptr )
        dlgBaudRate = new BaudRateDialog(this);
    dlgBaudRate->setBaudRate( this->baudRate );
    int ret=dlgBaudRate->exec();   //以模态方式显示对话框，用户关闭对话框时返回 DialogCode值
    if (ret==QDialog::Accepted)     //OK键被按下,对话框关闭，若设置了setAttribute(Qt::WA_DeleteOnClose)，对话框被释放，无法获得返回值
    { //OK键被按下，获取对话框上的输入，设置行数和列数
        this->baudRate = dlgBaudRate->getBaudRate();
        //保存到数据库,有更新，没有就插入
        Setting *setting = SettingServiceDao::instance().getSetting(Constant::BAUDRATE);
        if (setting) {
            setting->value = QString::number(this->baudRate);
            SettingServiceDao::instance().updateSetting(setting);
        } else {
            Setting *newSetting = new Setting();
            newSetting->key = Constant::BAUDRATE;
            newSetting->value = QString::number(this->baudRate);
            SettingServiceDao::instance().insertSetting(newSetting);
        }
        qDebug() << "设置后的波特率:" << this->baudRate;
        // 显示自动关闭的提示框，1秒后自动关闭
        MessageBoxUtils::showAutoCloseMessageBox(this, "提示", "波特率设置成功!");
    }

}
//初始化串口连接
void HomeWindow::initSerialPortService()
{
    // //连接串口
    serialPortService = new SerialPortService(this);
    //连接状态
    connect( serialPortService,&SerialPortService::connectionStatusChanged,this, [this](const ConnectionStatus status, const QString &message){
        setLabViewMeasureText("--"); //初始化
        labViewMessage->setText("测量信息：--");
        QString msg = "";
        switch (status) {
        case ConnectionStatus::Disconnected:
            msg = "心电设备未连接";
            break;
        case ConnectionStatus::Connecting:
            msg = "心电设备连接中...";
            break;
        case ConnectionStatus::Connected:
            isConnect = true;
            btnLinkDevice->setVisible( isConnect );
            msg = "心电设备已连接";
            m_worker->clear();
            break;
        case ConnectionStatus::ConnectionFailed:
            msg = "心电设备连接失败"+ message;;
            break;
        default:
            break;
        }
        labViewCord->setText( msg );
    });
    //数据回调
    connect( serialPortService,&SerialPortService::dataReceived,this, [this](const DataPacket &data){
        //这里处理接收到的数据
        //qDebug() << "MainWindow 接收到数据长度:";
        switch (data.type) {
        case 0://消息提示
            qDebug() << "MainWindow 接收到默认包:" << data.name;
            labViewMessage->setText("测量信息：" + data.name);
            break;
        case 1://数据包
            //qDebug() << "MainWindow 接收到消息包:" << data.name << ",搏动:" << data.jump << ",导联:" << data.lead;
            //这里把数据传送到自定义画波形的组件
            setLabViewMeasureText(QString("搏动：%1，导联状态：%2").arg(data.jump,data.lead));
            if( m_worker && data.data.size() > 0 ){
                QList<int> dataCopy = data.data; //复制数据，避免多线程冲突
                m_worker->pushPoint( dataCopy );
            }
            break;
        case 2://测量结果
            //qDebug() << "MainWindow 接收到心率包:" << data.res << ",心率:" << data.hr;
            setLabViewMeasureText( QString("心率：%1，结果：%2").arg(QString::number(data.hr),data.res) );
            break;
        }
    });
}
//初始化心电图组件
void HomeWindow::initECGWidget()
{
    qDebug("HomeWindow::initECGWidget");
    /***
    QVBoxLayout *mainLayout = new QVBoxLayout(ui->centralwidget);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    // --- 容器：用于叠加 --- waveWidget
    QWidget *waveWidget = new QWidget(ui->centralwidget);
    waveWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    **/
    // --- 叠加布局 ---
    QStackedLayout *stack = new QStackedLayout;
    stack->setStackingMode(QStackedLayout::StackAll);  // ✅ 必须设置这个，默认 StackOne 只显示一个
    ui->waveWidget->setLayout(stack);

    // --- 底层：网格 ---
    EcgGridWidget *grid = new EcgGridWidget(ui->waveWidget);
    grid->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // // --- 中层：波形 ---
    wave = new EcgWaveWidget(ui->waveWidget);
    wave->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // --- 顶层：文字标签容器 ---
    QWidget *labelContainer = new QWidget(ui->waveWidget);
    labelContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // 重要：否则可能被压缩为0
    //labelContainer->setStyleSheet("background-color: rgba(255, 0, 0, 80);");

    QVBoxLayout *vbox = new QVBoxLayout(labelContainer);
    vbox->setSizeConstraint( QLayout::SetMinimumSize );
    vbox->setContentsMargins(0, 0, 0, 0);
    vbox->addStretch();
    labViewMeasure = new QLabel("测量状态：--");
    labViewMeasure->setAlignment(Qt::AlignLeft);
    labViewMeasure->setSizePolicy( QSizePolicy::Expanding,QSizePolicy::Preferred);
    labViewMeasure->setStyleSheet("color:white; background-color:rgba(0,0,0,150); padding:5px 6px;");
    vbox->addWidget(labViewMeasure, 0,  Qt::AlignBottom);

    // --- 添加到叠层布局 ---
    stack->addWidget(grid);
    stack->addWidget(wave);
    stack->addWidget(labelContainer);
    stack->setCurrentWidget(wave);
    stack->setCurrentWidget(labelContainer);
    //放入主布局
    // mainLayout->addWidget(waveWidget);
}
//初始化增益和速度
void HomeWindow::initGainAndSpeed(){

    ui->radioButton_gain10->setChecked( true );
    ui->radioButton_speed25->setChecked( true );
    //增益选择
    connect( ui->buttonGroupGain , &QButtonGroup::buttonClicked,
            this, [this](QAbstractButton *button) {
            QString  gain = button->text();
            wave->setGain(gain.toDouble());
    });
    //速度选择
    connect( ui->buttonGroupSpeed , &QButtonGroup::buttonClicked,
            this, [this](QAbstractButton *button) {
                QString  speed = button->text();
                wave->setSpeed(speed.toDouble());
            });
}
//实时测量标签
void HomeWindow::setLabViewMeasureText(const QString &txt)
{
    //更新测量状态文本
    QString msg =  QString("测量状态：%1").arg(txt);
    labViewMeasure->setText(msg);
}
//初始化模拟数据
void HomeWindow::initSimulateData(){
    //设置ui->pushButton_start 悬浮背景颜色改变
    ui->pushButton_start->setButtonType(QPushButtonWidget::ButtonType::TYPE_DEFAULT);
    connect(ui->pushButton_start, &QPushButtonWidget::clicked, this, [this](){
        qDebug() << "开始模拟数据";
        if( timer ) return;
        //查找文件
        QString currentWorkDir = Config::currentWorkDir();
        //向上移动两级目录  这里根据自己情况调整，模拟数据的源数据在 源代码根目录
        currentWorkDir = PathUtils::moveUpLevels(currentWorkDir, 3);
        QString ecg_sample_data_path = currentWorkDir + "/ecg_sample_data.bin";
        qDebug() << "模拟数据文件路径:" << ecg_sample_data_path;
        BinaryFileUtil *fileUtil =  new  BinaryFileUtil(ecg_sample_data_path, this);
        fileUtil->resetReadPos();
        timer = new QTimer(this);
        serialPortService->setTest(true); //设置为测试模式
        connect(timer, &QTimer::timeout, this, [fileUtil,this](){
            //这里没有硬件设备模拟数据
            QByteArray data = fileUtil->readBytes( 6 ); //重置读取位置
            if( data .size() <= 0 ){
                fileUtil->resetReadPos();
                return;
            }
            if( serialPortService ){
                serialPortService->displayReceivedData( data );
            }
        });
        timer->start(20); // 每150ms产生一次数据
        ui->pushButton_start->setEnabled(false);
        ui->pushButton_start->setText("已开始");
        ui->pushButton_stop->setEnabled(true);
        serialPortService->startWork();
    });
    ui->pushButton_stop->setButtonType(QPushButtonWidget::ButtonType::TYPE_DANGER);
    connect(ui->pushButton_stop, &QPushButtonWidget::clicked, this, [this](){
        qDebug() << "停止模拟数据" ;
        if (timer && timer->isActive()) {
            ui->pushButton_start->setEnabled(true);
            ui->pushButton_start->setText("开始模拟");
            ui->pushButton_stop->setEnabled(false);
            timer->stop();//先停止
            timer->deleteLater();//标记删除
            timer = nullptr;// 指针置空
            serialPortService->stopWork();
        }
    });
}
///数组组装
void HomeWindow::setupWorker() {
    m_worker = new ConcurrentWorker(this);
    // 连接信号槽
    connect(m_worker, &ConcurrentWorker::dataProduced,
            this, &HomeWindow::onDataProduced);
    connect(m_worker, &ConcurrentWorker::started,
            this, &HomeWindow::onWorkerStarted);
    connect(m_worker, &ConcurrentWorker::stopped,
            this, &HomeWindow::onWorkerStopped);
     m_worker->start(); //开启
}
void HomeWindow::onDataProduced(const QList<int> &data) {
    // 处理接收到的数据
    if (wave) {
        wave->addDataPoint(data);
    }
}
void HomeWindow::onWorkerStarted() {
    qDebug() << "数据生产者线程已启动";
}
void HomeWindow::onWorkerStopped() {
    qDebug() << "数据生产者线程已停止";
}
